package com.excesys.util;

import ch.qos.logback.core.util.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {

    public static void main(String[] args) throws IOException {
//        String str = "煎饼果子";
//        byte[] bytes = str.getBytes();
//        byte[] gzipBytes = gzip(bytes);
//        byte[] unGzipBytes = unGzip(gzipBytes);
//        String value = byteToHexString(unGzipBytes);
//        String finalString = getFinalString(str);
//        System.out.println(value);
//        System.out.println(finalString);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://img08.tooopen.com/20240104/tooopen_s0950505050441de27f-063b-4b4b-ac70-34defdade991.jpg");
        httpGet.setHeader("Referer", "https://www.tooopen.com/img/88_282.html");
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
        CloseableHttpResponse response = httpClient.execute(httpGet); // 发送GET请求
        HttpEntity entity = response.getEntity(); // 获取响应体
        byte[] bytes = EntityUtils.toByteArray(entity); // 将响应体转换为字节数组
        FileOutputStream out = new FileOutputStream("1.jpg"); // 创建文件输出流
        out.write(bytes); // 将字节数组写入文件
        out.close(); // 关闭文件输出流
        response.close(); // 关闭响应
        httpClient.close(); // 关闭HttpClient
        System.out.println("Image download successfully."); // 输出下载成功信息
    }

    public static void downloadFile(String downloadUrl, String path, Map headers) {
        FileOutputStream fos = null;
        HttpResponse execute = HttpRequest.get(downloadUrl).addHeaders(headers).execute();
        try {
            //使用bufferedInputStream 缓存流的方式来获取下载文件，不然大文件会出现内存溢出的情况
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            } else {
                FileUtil.createMissingParentDirectories(file);
            }
            fos = new FileOutputStream(file);
            fos.write(execute.bodyBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fos);
        }
    }

    public static byte[] gzip(byte[] content) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        ByteArrayInputStream bais = new ByteArrayInputStream(content);
        byte[] buffer = new byte[1024];
        int n;
        while ((n = bais.read(buffer)) != -1) {
            gos.write(buffer, 0, n);
        }
        gos.flush();
        gos.close();
        return baos.toByteArray();
    }

    public static byte[] unGzip(byte[] content) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(content));
        byte[] buffer = new byte[1024];
        int n;
        while ((n = gis.read(buffer)) != -1) {
            baos.write(buffer, 0, n);
        }

        return baos.toByteArray();
    }

    public static String byteToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length);
        String sTemp;
        for (int i = 0; i < bytes.length; i++) {
            sTemp = Integer.toHexString(0xFF & bytes[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static String getFinalString(String str) throws IOException {
        //1.转字节数组
        byte[] bytes = str.getBytes();
        //2.压缩字节数组
        byte[] gzip = gzip(bytes);
        //3.将压缩的字节数组再解压
        byte[] unGzip = unGzip(gzip);
        //4.将解压的字节数组转为字符串
        String value = byteToHexString(unGzip);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("%");
        int count = 0; // %E5%A4%A7%E9%97%B8%E8%9F%B9
        for (int i = 0; i < value.length(); i++) {
            count++;
            if (count == 3) {
                count = 1;
                stringBuilder.append("%");
            }
            char charStr = value.charAt(i);
            stringBuilder.append(charStr);
        }
        return stringBuilder.toString();
    }

}
